package com.taotao.portal.controller;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.portal.pojo.CartItem;
import com.taotao.portal.service.ICartService;

@Controller
@RequestMapping("/cart")
public class CartController {

	@Autowired
	private ICartService cartService;

	/**
	 * 添加到购物车
	 * 
	 * @param itemId
	 * @param num
	 * @param request
	 * @param response
	 * @return
	 */
	// http://localhost:8082/cart/add/147934739912093.html
	@RequestMapping("/add/{itemId}")
	public String AddItemToCart(@PathVariable Long itemId,
			@RequestParam(defaultValue = "1") Integer num,
			HttpServletRequest request, HttpServletResponse response) {
		TaotaoResult taotaoResult = this.cartService.AddItemToCart(itemId, num,
				request, response);
		if (200 == taotaoResult.getStatus()) {
			return "redirect:/cart/success.html";
		}
		return null;
	}

	/**
	 * 跳转页面
	 * 
	 * @return
	 */
	@RequestMapping("/success")
	public String success() {
		return "cartSuccess";
	}

	/**
	 * 显示购物车
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	// http://localhost:8082/cart/cart.html
	@RequestMapping("/cart")
	public String getCartItemList(HttpServletRequest request, Model model) {
		List<CartItem> cartItems = this.cartService.getCartItemList(request);
		model.addAttribute("cartList", cartItems);
		return "cart";
	}

	/**
	 * 修改数量
	 * 
	 * @param request
	 * @param response
	 * @param itemId
	 * @param num
	 * @return
	 */
	// http://localhost:8082/cart/update/num/147934739912093/4.action
	@RequestMapping(value = "/update/num/{itemId}/{num}")
	@ResponseBody
	public TaotaoResult updateCartItemCount(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Long itemId,
			@PathVariable Integer num) {
		TaotaoResult taotaoResult = this.cartService
				.updateCartItemCountByItemId(request, response, itemId, num);
		return taotaoResult;
	}

	// http://localhost:8082/cart/delete/147934739912093.html
	@RequestMapping(value = "/delete/{itemId}")
	public String deleteCartItem(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Long itemId) {
		TaotaoResult taotaoResult = this.cartService.deleteCartItem(request,
				response, itemId);
		if (200 == taotaoResult.getStatus()) {
			return "redirect:/cart/cart.html";
		}
		return null;
	}
}
